<?php
/**
 * @author Jumper Swordwave
 * date: 2021/04/19
 */
declare(strict_types=1);
namespace App\Game\Core;

use Psr\Container\ContainerInterface;

use App\Constants\ErrorCode;

/**
 * 请求匹配转发
 */
class Dispatch 
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * @var Route
     */
    private $route;
    
    public function __construct(ContainerInterface $container, Route $route)
    {
        $this->container = $container;
        $this->route = $route;
    }

    public function execute(Request $request)
    {
        try {
            list($class, $action) = $this->route->match($request->getCommand());
            $obj = $this->container->get($class);
            if ($obj) {
                return $obj->$action($request);
            }
            
            return Response::error(ErrorCode::SERVER_NOTFOUND, '请求目标不存在');
        } catch(RouteException $e) {
            return Response::error($e->getCode(), $e->getMessage());
        }
    }
}